import { ChangeDetectionStrategy, ChangeDetectorRef, Component } from '@angular/core';
import type { OptionItem } from '@iux/live';

@Component({
  selector: 'app-quick-add',
  templateUrl: './quick-add.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class QuickAddComponent {
  options: OptionItem[] = [
    { value: 1, label: 'Option 1', isLeaf: true },
    { value: 2, label: 'Option 2', isLeaf: true },
    { value: 3, label: 'Option 3', isLeaf: true },
  ];
  value: number | string;

  constructor(private cdr: ChangeDetectorRef) {}

  handleAddOption = (inputValue: string): void => {
    const set = new Set(this.options.map(item => item.value));
    if (set.has(inputValue)) {
      this.options = [...this.options];
      return;
    }
    this.options = [...this.options, { value: inputValue, label: inputValue, isLeaf: true }];
  };

  handleAddAndSelectOption = (inputValue: string): void => {
    this.value = inputValue;
    const set = new Set(this.options.map(item => item.value));
    if (set.has(inputValue)) {
      this.options = [...this.options];
      return;
    }
    this.options = [...this.options, { value: inputValue, label: inputValue, isLeaf: true }];
  };

  handleAddOptionAsync = (inputValue: string): Promise<void> =>
    new Promise((resolve): void => {
      setTimeout(() => {
        this.options = [...this.options, { value: inputValue, label: inputValue, isLeaf: true }];
        resolve();
      }, 1000);
    });
}
